import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input, Row, Col, Select } from 'antd';
import moment from 'moment';
import router from 'umi/router';
import SelectForm from '@/components/SelectForm';
import RightDraw from '@/components/RightDraw';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import prompt from '@/components/Prompt';
import AntdFormItem from '@/components/AntdFormItem';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import FileImportPlus from '@/components/FileImport/FileImportPlus';
import { queryDict, formateDateToMin } from '@/utils/common';
import AdSearch from '@/components/AdSearch';
import AdSelect from '@/components/AdSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import { allDictList } from '@/utils/constans';
import {
  selectPlusList,
  saveAllValues,
  codes,
  allDispatchType,
  routeUrl,
  selectDeclareDetailAndInfo,
  formate,
  formateNOSecond,
  renderTableAdSelect,
  declareStatus,
} from './utils';
import DeclareDetailPlus from './DeclareDetailPlus';
import styles from './declare.less';

const { confirm } = Modal;
const { Option } = Select;

@ManageList
@connect(({ declare, loading, component }) => ({
  // declareDetail: declare.declareDetail,
  formValues: declare.formValues,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.listPlus],

  manifestPlusList:declare.manifestPlusList,
  manifestPlusDetail:declare.manifestPlusDetail,
}))
@Form.create()
export default class DeclareListPlus extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      visible: false,
      visibleFile: false,
      detailId: '',
      // selectedRows: [],
      company: [],
      importType: 'add',
      ICcardList: [],
      icCardId: '',
    };
    this.className = 'declare-table';
  }
  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.manifest_transport, allDictList.manifest_goods,allDictList.declareListType];
    queryDict({ props: this.props, allDict });
  }
  componentDidMount() {
    selectPlusList({ props: this.props });
    // this.getIClist();
  }
  selectDeclareListCall = () => {
    this.callData();
  };
  callData = res => {
    console.log('res.data---',res)
    if (res && res.code === 0) {
      selectPlusList({ props: this.props, call: res.data });
    }
  };

  //右侧弹窗详情页---修改
  getDeclareDetailAndInfo = () => {
    const { detailId } = this.state;
    selectDeclareDetailAndInfo({
      type: allDispatchType.detailPlus,
      payload: { id: detailId },
      props: this.props,
    });
  };

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    const props = { props: this.props };
    form.resetFields();
    saveAllValues({ payload: { formValues: {} }, ...props });
    selectPlusList({ ...props });
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    if (!formValues) return;
    const { company } = this.state;
    const { loadTime, unloadTime, ...value } = formValues;
    if (loadTime) {
      value.loadTime = moment(loadTime).format(formateNOSecond);
    }
    if (unloadTime) {
      value.unloadTime = moment(unloadTime).format(formateNOSecond);
    }
    const params = { props: this.props, payload: value };
    saveAllValues({ payload: { formValues: value }, props: this.props });
    selectPlusList(params);
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.props;
    // console.log('formValues', formValues, 'param', param);
    selectPlusList({ payload: { ...formValues, ...param }, props: this.props });
  };

  //详情
  showDetail = (e, detailId) => {
    e.stopPropagation();
    this.handleStateChange([{ detailId }, { visible: true }]);
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //新建
  handleAdd = () => {
    // router.push(routeUrl.add);
    this.handleImportFile('add');
  };
  //导入：
  handleImportFile = importType => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile, importType });
    // this.getIClist();
  };
  //IC卡列表：
  getIClist = () => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.ICcardList,
      payload: { pageSize: 100 },
      callback: data => {
        this.setState({
          ICcardList: data,
        });
      },
    });
  };

  //编辑
  handleEdit = () => {
    const { detailId } = this.state;
    this.handleStateChange([{ visible: false }]);
    router.push(`${routeUrl.detailPlus}/${detailId}`);
  };

  columns = [
    {
      title: '单据号',
      dataIndex: 'manifestOwnNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id, record.status)}
          text={text}
          code={codes.showDetailPlus}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: text => renderTableAdSelect({ 
        props: this.props, 
        value: text, 
        key: allDictList.declareListType,
        declare: false,
      }),
      width: 100,
    },
    {
      title: '货物运输批次号',
      dataIndex: 'manifestNo',
      // render: (text, record) => (
      //   <AdButton
      //     mode="a"
      //     onClick={() => this.showDetail(record.id, record.status)}
      //     text={text}
      //     code={codes.showDetail}
      //   />
      // ),
      // fixed: this.props.isMobile ? false : true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: text => renderTableAdSelect({ props: this.props, value: text, data: declareStatus }),
      width: 100,
    },
    {
      title: '运输方式',
      dataIndex: 'transportMethodCode',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.manifest_transport,
          declare: true,
        }),
    },
    {
      title: '进出境口岸海关',
      dataIndex: 'customsCode',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.manifest_goods,
          declare: true,
        }),
    },
    {
      title: '承运人代码',
      dataIndex: 'carrierBy',
    },
    {
      title: '运输工具代理企业代码',
      dataIndex: 'enterpriceCode',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '货物装载时间',
      dataIndex: 'loadTime',
    },
    {
      title: '装货地代码',
      dataIndex: 'unloadCode',
    },
    {
      title: '到达卸货地日期',
      dataIndex: 'unloadTime',
    },
    {
      title: '传输企业备案关区',
      dataIndex: 'filingAreaCode',
    },
    {
      title: '舱单传输人名称',
      dataIndex: 'transprotName',
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  onRef = ref => {
    this.child = ref;
  }

  // 提交
  commitDeclare = flag => {
    this.child.commitDeclare();
  };
  changeIC = val => {
    this.setState({
      icCardId: val,
    });
  };

  render() {
    const { manifestPlusList, loading, form, isMobile, dictObject, manifestPlusDetail } = this.props;
    const {
      expandForm,
      detailId,
      visible,
      selectedRows,
      visibleFile,
      importType,
      ICcardList,
      icCardId,
    } = this.state;
    const importUrl =
    // POST /mds-road-manifest/importMdsRoadManifestByPreplan  |importMdsRoadManifest
      importType == 'add' ? 'importMdsRoadManifestByPreplan' : `importMdsRoadManifestByPreplan?id=${detailId}`;

    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="货物运输批次号" code="manifestNo" {...commonParams}>
        <Input />
      </AntdFormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="status" {...commonParams}>
        <AdSelect isExist={true} data={declareStatus} mode="multiple" />
      </AntdFormItem>
    );
    // const secondFormItem = (
    //   <AntdFormItem label="运输方式" code="transportMethodCode" {...commonParams}>
    //     <AdSelect isExist={true} data={dictObject[allDictList.manifest_transport]} />
    //   </AntdFormItem>
    // );
    // secondForm 参数
    const otherFormItem = [
      [
        <AntdFormItem label="进出境口岸海关" code="customsCode" {...commonParams}>
          <Input />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="承运人代码" code="carrierBy" {...commonParams}>
          <Input />
        </AntdFormItem>,
        <AntdFormItem label="运输工具代理企业" code="enterpriceCode" {...commonParams}>
          <Input />
        </AntdFormItem>,
        // <AntdFormItem label="装载日期" code="loadTime" {...commonParams}>
        //   <AntdDatePicker showTime={{ format: 'HH:mm' }} />
        // </AntdFormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.selectPlus,
    };

    const tableButtonsParams = {
      handleAdd: this.handleAdd,
      code: codes.addPlus,
    };

    // 详情 参数
    const detail = manifestPlusDetail ? manifestPlusDetail[detailId] || {} : {};
    const _status = detail.status == 'COMMIT';

    const rightDrawParams = {
      isMobile,
      visible,
      title: '预配舱单详情',
      code: codes.showDetailPlus,
      mode: 'rightDraw',
      closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
      buttons: (
        <Button.Group>
          <AdButton
            onClick={() => this.commitDeclare(0)}
            disabled={_status}
            text="提交"
            code={codes.commit}
          />
          {/* <AdButton
            disabled={_status}
            onClick={() => this.handleImportFile('edit')}
            text="导入"
          /> */}
          {/* <AdButton
            disabled={_status}
            onClick={() => this.handleEdit()}
            text="编辑"
          /> */}
        </Button.Group>
      ),
    };

    const extraParam = (
      <div className={styles.tableListForm}>
        <Form layout="inline">
          <Row>
            <Col md={12} sm={24}>
              <Form.Item label="IC卡">
                {form.getFieldDecorator('icCardId', {
                  initialValue: undefined,
                })(
                  <Select placeholder="请选择" onChange={this.changeIC}>
                    <Option value="">请选择</Option>
                    {ICcardList &&
                      ICcardList.map(item => <Option key={item.id}>{item.name}</Option>)}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
    );

    return (
      <Fragment>
        <FileImportPlus
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`mds/mds-road-manifest/${importUrl}`} //导入地址
          // urlImport={`mds/mds-road-manifest/${importUrl}?icCardId=${icCardId}`} //导入地址,添加IC卡
          queryData={[this.selectDeclareListCall]}
          urlCase={`attachment/预配舱单模板.xlsx`}
          accept=".xls,.xlsx"
          callData={this.callData}
          isICCard={true} // 只用于给预配/原始舱单 使用，做下拉框的显示与否
          isPlus={true} //用于判断给预配/原始舱单 传值用
        // extra={extraParam}
        />
        <SelectForm {...selectFormParams} className={styles.declareWrap} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          loading={loading}
          data={manifestPlusList}
          // selectedRows={selectedRows}
          // onSelectRow={selectedRows => {
          //   this.handleStateChange([{ selectedRows }]);
          // }}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
          // getCheckboxProps={record => {
          //   const status = record.status;
          //   const checked = status === 'DRAFT' || status === 'BACK';
          //   return !checked;
          // }}
          disabledRowSelected={true}
        />
        <RightDraw {...rightDrawParams}>
          <DeclareDetailPlus
            detailId={detailId}
            pageType="rightDraw"
            commitDeclare={this.commitDeclare}
            onRef={this.onRef}
          />
        </RightDraw>
      </Fragment>
    );
  }
}
